﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Diagnostics;

namespace ESRP
{
    /// <summary>
    /// Macheta pentru definirea conturilor corespondente
    /// test
    /// </summary>
    public partial class ConturiCorespFrm : FrmRezumat
    {
        public ConturiCorespFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            workConnString = mInfo.workConnectionString;
            this.eSRPDataSet.ConturiCoresp.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            ActiveControl = conturiCorespDGV;
        }

        private void ConturiCorespFrm_Load(object sender, EventArgs e)
        {

            SetCurentUnit(ModuleInfo.CodUnitate);

            if (jurnaleBindingSource.Count != 0)
            {
                this.listBndSourceMain.Add(fKConturiCorespJurnaleBindingSource);
            }
            else
            {
                conturiCorespDGV.DataSource = conturiCorespBindingSource;
                this.listBndSourceMain.Add(conturiCorespBindingSource);
                this.eSRPDataSet.ConturiCoresp.IdJurnalColumn.DefaultValue = 0;
            }

            this.listTableAdaptor.Add(conturiCorespTableAdapter.Adapter);

            if (!EsteArhiva())
            {
                AddButton("Salvare", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                AddButton("Conturi", global::ERPStudio.Properties.Resources._001_07, RezumatConturi, ToolStripItemAlignment.Right, false);
                /// functia care se apeleaza in momentul in care se apasa F9
                HandleSalvare += new EventHandler(Salvare);
            }

        }
        private void RezumatConturi(object sender, EventArgs e)
        {
            ConturiRezumatFrm rez = new ConturiRezumatFrm(ModuleInfo);
            rez.SelectionAddOn = true;
            if (rez.ShowDialog() == DialogResult.OK)
            {
                this.conturiCorespDGV.CurrentCell.Value =
                    rez.selectedRow.Cells["ContColumn"].Value;
                if (this.conturiCorespDGV.CurrentCell.IsInEditMode)
                    this.conturiCorespDGV.EditingControl.Text = rez.selectedRow.Cells["ContColumn"].Value.ToString();
            }
        }
        override public void SetCurentUnit(short vCodUnitate)
        {
            ModuleInfo.CodUnitate = vCodUnitate;
            this.jurnaleTableAdapter.Connection = DeschideConexiune(workConnString);
            try
            {
                SqlCommand cmd = new SqlCommand("InitConturiCoresp", this.jurnaleTableAdapter.Connection);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MyTrace("Eroare initializare conturi corespondente!" + ex.ToString());
                MessageBox.Show("Eroare initializare conturi corespondente!" + ex.ToString());
            }

            this.jurnaleTableAdapter.Fill(this.eSRPDataSet.Jurnale, ModuleInfo.CodUnitate);
            this.conturiCorespTableAdapter.Connection = this.jurnaleTableAdapter.Connection;
            this.conturiCorespTableAdapter.Fill(this.eSRPDataSet.ConturiCoresp, ModuleInfo.CodUnitate);
            InchideConexiune(this.jurnaleTableAdapter.Connection);
            if (jurnaleBindingSource.Count == 0)
            {
                jurnalL.Visible = false;
                jurnalCB.Visible = false;
            }
            if (jurnalCB.Items.Count > 0)
                jurnalCB.SelectedIndex = 0;
        }
        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup(conn);
        }

        private void conturiCorespDGV_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            Object oVal = conturiCorespDGV[e.ColumnIndex, e.RowIndex].Value;
            if(oVal==null)
                return;
            String oldValue = oVal.ToString();
            String newValue = conturiCorespDGV[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString();
            if (newValue == String.Empty)
                return;
            if (ExistaContTerminal(newValue) == 0)
            {
                MessageBox.Show("Contul " + newValue + " are analitice si nu pot fi inregistrate miscari pe el!",
                       "Stop",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Stop);
                return;
            }
            if (newValue == oldValue)
                return;
            if (MessageBox.Show("Doriti modificarea tuturor conturilor " + oldValue + " cu contul " + newValue + "?",
                "Decizie",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.No)
                return;
            StatusProgressBar.Value = 0;
            StatusProgressBar.Maximum = conturiCorespDGV.Rows.Count - 1;
            String nCol = conturiCorespDGV.Columns[e.ColumnIndex].DataPropertyName;

            if(jurnaleBindingSource.Count != 0)
            {
                for (int i = 0; i < fKConturiCorespJurnaleBindingSource.Count; i++)
                {
                    if (((DataRowView)fKConturiCorespJurnaleBindingSource[i]).Row[nCol].ToString() == oldValue)
                        ((DataRowView)fKConturiCorespJurnaleBindingSource[i]).Row[nCol] = newValue;
                    StatusProgressBar.Value++;
                }
            }
            else
            {
                foreach (DataGridViewRow dr in conturiCorespDGV.Rows)
                {
                    if (dr.Index == e.RowIndex)
                        continue;
                    if (dr.Cells[e.ColumnIndex].Value != null &&
                        dr.Cells[e.ColumnIndex].Value.ToString() == oldValue)
                        dr.Cells[e.ColumnIndex].Value = newValue;
                    StatusProgressBar.Value++;
                }
            }
            conturiCorespDGV.Update();
            

        }
        private Int16 ExistaContTerminal(String cont)
        {
            Int16 ret = 0;
            SqlCommand cmd = new SqlCommand("", FrmRezumat.DeschideConexiune(workConnString));
            cmd.CommandText = "SELECT [Cont] FROM [Conturi] WHERE [Terminal]=1 AND [Cont]='" + cont + "' AND [CodUnitate]=" + ModuleInfo.CodUnitate.ToString();
            Object retObj = cmd.ExecuteScalar();
            if (retObj != null && retObj != DBNull.Value)
                ret = 1;
            InchideConexiune(cmd.Connection);
            cmd.Dispose();
            return ret;
        }

        private void conturiCorespDGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.FormattedValue.ToString() == String.Empty)
                return;
            if (ExistaContTerminal(e.FormattedValue.ToString()) == 0)
            {
                MessageBox.Show("Contul " + e.FormattedValue.ToString() + " are analitice si nu pot fi inregistrate miscari pe el!",
                       "Stop",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Stop);
                e.Cancel = true;
                return;
            }

        }

        private void conturiCorespDGV_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            
        }
        /// <summary>
        /// cand se apasa enter, controlul activ este luna, anul
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {

        }

    }
}
